<?php

namespace app\admin\controller\xilumarket\discover;

use app\admin\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use app\common\controller\Backend;
use app\common\model\xilumarket\UserAuth;
use app\admin\model\xilumarket\discover\Topic AS TopicModel;
use app\common\model\xilumarket\Topic as XilumarketTopic;
use app\common\model\xilumarket\TopicUser;

/**
 * 话题管理
 *
 * @icon fa fa-circle-o
 */
class Topic extends Backend
{
    protected $searchFields = 'name,description';
    protected $multiFields = ['status','top_status'];
    protected $noNeedRight = ['selectpage'];
    /**
     * Topic模型对象
     * @var \app\admin\model\xilumarket\discover\Topic
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TopicModel;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("topStatusList", $this->model->getTopStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
       return parent::index();
    }

    public function multi_add()
    {
        if($this->request->isAjax()){
            $key = input('key');
            $keys = explode(',', $key);
            $allData = [];
            foreach($keys as $key) {
                $allData[] = [
                    'name'  => $key,
                ];
            }
            $topic = new XilumarketTopic();
            $topic->saveAll($allData);
            $this->success('成功');
        }
        return $this->fetch();
    }


    public function add() {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                
                $params['province_id'] = $this->request->post('province');
                $params['city_id'] = $this->request->post('city');
                $params['region_id'] = $this->request->post('region');

                $result = $this->model->save($params);
                if ($result === false) {
                    Db::rollback();
                    $this->error($this->model->getError());
                }
                Db::commit();
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                $params['province_id'] = $this->request->post('province');
                $params['city_id'] = $this->request->post('city');
                $params['region_id'] = $this->request->post('region');
                
                $result = $row->save($params);
                if ($result === false) {
                    Db::rollback();
                    $this->error($row->getError());
                }
                Db::commit();
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->with('children')->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    #1.是否有帖子
                    $goods_count = \app\admin\model\xilumarket\discover\TopicForum::where("topic_id",$v['id'])->count();
                    if($goods_count>0){
                        Db::rollback();
                        $this->error($v['name'].'有帖子，不可删除');
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function users($ids) {
        if(!$ids){
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list(, $sort, , $offset, $limit) = $this->buildparams();
            $list = TopicUser::where(['topic_id' => $ids])->with(['user'])
                ->order($sort)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->user->avatar = $v->user->avatar ? cdnurl($v->user->avatar, true) : letter_avatar($v->user->nickname);
                $v->visible(['user.nickname', 'user.avatar', 'user.id', 'user.mobile', 'user.gender', 'id', 'createtime', 'is_admin']);
            }
            // $auth_count = UserAuth::where('check_status',0)->count(1);
            $result = array("total" => $list->total(), "rows" => $list->items(),"extend" => []);

            return json($result);
        }
        return $this->fetch('', ['id'=>$ids]);
    }

    public function setTopicAdmin($id){
        $tUser = TopicUser::find($id);
        if($tUser->is_admin == '11'){
            $this->error('当前用户已经是吧主了');
        }
        TopicUser::where(['topic_id'=>$tUser->topic_id, 'is_admin' => '11'])->update(['is_admin' => '00']);
        $tUser->is_admin = '11';
        $tUser->save();
        $this->success();
    }

    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }

}
